package com.sayice.robotconflict

import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.OnBackPressedCallback
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.sayice.robotconflict.ui.theme.RobotConflictTheme
import com.sayice.robotconflict.view.page.*
import com.sayice.robotconflict.view.route.Route
import com.sayice.robotconflict.viewmodel.GameViewModel
import kotlinx.coroutines.launch


class MainActivity : ComponentActivity() {
    private val viewModel: GameViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        WindowCompat.setDecorFitsSystemWindows(window, false)
        lifecycleScope.launch {
            viewModel.toastFlow.flowWithLifecycle(lifecycle, Lifecycle.State.STARTED)
                .collect {
                    Toast.makeText(this@MainActivity, it, Toast.LENGTH_SHORT).show()
                }
        }
        setContent {
            val navController = rememberNavController()
            var openQuitDialog by remember { mutableStateOf(false) }
            val context = LocalContext.current
            LaunchedEffect(Unit) {
                onBackPressedDispatcher.addCallback(
                    context as MainActivity,
                    object : OnBackPressedCallback(true) {
                        override fun handleOnBackPressed() {
                            openQuitDialog = true
                        }
                    })
                viewModel.pageFlow.collect {
                    navController.navigate(it.name)
                }
            }
            RobotConflictTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    MainNavHost(navController, viewModel)
                    if (openQuitDialog) {
                        AlertDialog(
                            onDismissRequest = { openQuitDialog = false },
                            title = { Text("退出游戏？") },
                            confirmButton = {
                                TextButton(onClick = {
                                    finish()
                                    viewModel.disConnect()
                                }) {
                                    Text("确定")
                                }
                            },
                            dismissButton = {
                                TextButton(onClick = { openQuitDialog = false }) {
                                    Text("取消")
                                }
                            }
                        )
                    }
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        hideSystemBars()
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        hideSystemBars()
    }

    /**
     * 隐藏系统栏
     */
    private fun hideSystemBars() {
        WindowInsetsControllerCompat(window, window.decorView).let { controller ->
            controller.hide(WindowInsetsCompat.Type.systemBars())
            controller.systemBarsBehavior =
                WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
        }
    }
}

@Composable
fun MainNavHost(navController: NavHostController, viewModel: GameViewModel) {
    NavHost(navController = navController, startDestination = Route.LOGIN.name) {
        composable(route = Route.LOGIN.name) {
            Login(viewModel)
        }
        composable(route = Route.HALL.name) {
            Hall(viewModel)
        }
        composable(route = Route.PLAYER_CENTER.name) {
            PlayerCenter(viewModel)
        }
        composable(route = Route.FRIENDS.name) {
            Friends(viewModel)
        }
        composable(route = Route.TEAM_ROOM.name) {
            TeamRoom(viewModel)
        }
        composable(route = Route.MATCH.name) {
            Match(viewModel)
        }
        composable(route = Route.PLAY.name) {
            Play(viewModel)
        }
    }
}